# -*- coding: utf-8 -*-
import socket
import threading
from multiprocessing import Process, Queue
#import dataParse
import struct
import pymysql
import datetime
import select
import os 
import json
import types
import sys
sys.getdefaultencoding()

def wirteDB(data):
	#写入数据库
	# tmp=[]
	# dat = (data[0], data[1],data[2],datetime.datetime.now())
	# tmp.append(dat)
	conn = pymysql.connect("localhost", "root", "1234","moyan",charset="utf8")
	print("连接成功")
	# 使用cursor()方法获取操作游标
	cursor = conn.cursor()
	#2. SQL 插入语句
	sql = """INSERT INTO historydata(id_id, name, power, state, ntime) VALUES ( '%d', '%s', '%s', '%s', '%s')"""
	   # 执行sql语句
	cursor.execute((sql %(data[0], data[1], data[2], data[3], datetime.datetime.now())).encode('utf-8'))
	#cursor.executemany(sql ,tmp)
	conn.commit()
	print("数据写入数据库成功",datetime.datetime.now())
	# 提交到数据库执行
	# 关闭数据库连接
	conn.close()

def WriteDBProcess(q):
	while True:
		
		#data = data.encode('utf-8')
		data=[{"name": "电水壶", "id": 1234, "power": "15", "state": "0"}]
		for elem in data:
			#print(elem['name'].encode('utf-8'))
			datas =[]
			datas.append(elem['id'])
			datas.append(elem['name'])
			datas.append(elem['power'])
			datas.append(elem['state'])
			#print(elem['id'],elem['name'],elem['state'],elem['power'])
		print(datas)
		wirteDB(datas)

		#print(data,type(data))
		
		

def main():
	q = Queue()
	#启动进程server
	#prev=Process(target=server, args=(q,))
	#启动京城WriteDB
	ploc=Process(target=WriteDBProcess,args=(q,))
	#prev.start()
	ploc.start()

if __name__ == '__main__':
	main()